from datetime import datetime
import random
import re
from flask import current_app, jsonify
from flask import json
from flask import make_response
from flask import request
from flask import session

from info import constants, db
from info import redis_store #None
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue


@passport_blue.route('/logout', methods=['POST'])
def logout():
    session.pop("user_id",None)
    session.pop("nick_name",None)
    session.pop("user_mobile",None)
    session.pop("is_admin",None)

    return jsonify(errno=RET.OK,errmsg = "退出成功")

@passport_blue.route('/login', methods=['POST'])
def login():
    dict_data = request.json
    mobile = dict_data.get("mobile")
    password = dict_data.get("password")
    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR,errmsg = "参数不完整")
    try:
        user = User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "获取用户失败")
    if not user:
        return jsonify(errno=RET.NODATA,errmsg = "该用户不存在")
    # if user.password_hash != password:
    if not user.check_password(password):
        return jsonify(errno=RET.DATAERR,errmsg = "密码错误")

    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["user_mobile"] = user.mobile

    user.last_login = datetime.now()
    # try:
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)

    return jsonify(errno=RET.OK,errmsg = "登陆成功")



@passport_blue.route('/register', methods=['POST'])
def register():
    # json_data = request.data
    # dict_data = json.loads(json_data)

    dict_data = request.get_json()
    mobile = dict_data.get("mobile")
    sms_code = dict_data.get("sms_code")
    password = dict_data.get("password")

    if not all([mobile,sms_code,password]):
        return jsonify(errno=RET.PARAMERR,errmsg = "参数不完整")

    try:
        redis_sms_code = redis_store.get("sms_code:%s"%mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "获取短信验证码失败")
    if not redis_sms_code:
        return jsonify(errno=RET.NODATA,errmsg = "短息验证码已过期")
    try:
        redis_store.delete("sms_code:%s"%mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "删除短息验证码失败")
    if sms_code != redis_sms_code:
        return jsonify(errno=RET.DATAERR,errmsg = "短息验证码填写错误")
    user = User()
    user.nick_name = mobile
    user.password = password
    user.mobile = mobile
    user.signature = "这个人很懒，什么都没有"
    try:
        db.session.add(user)
        db.session.commit()

    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg = "注册用户失败")
    return jsonify(errno=RET.OK,errmsg = "注册成功")







@passport_blue.route('/sms_code', methods=['POST'])
def sms_code():
    json_data = request.data
    dict_data = json.loads(json_data)
    mobile = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")

    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno = RET.PARAMERR,errmsg="参数不完整")

    if not re.match("1[356789]\\d{9}",mobile):
        return jsonify(errno=RET.DATAERR,errmsg = "手机号格式不正确")
    try:
        redis_image_code = redis_store.get("image_code:%s"%image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "图片验证码获取失败")
    if not redis_image_code:
        return jsonify(errno=RET.NODATA,errmsg = "图片验证码已过期")
    try:
        redis_store.delete("image_code:%s"%image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        jsonify(errno=RET.DBERR,errmsg = "删除图片验证码失败")

    if image_code.lower()!=redis_image_code.lower():
        return jsonify(errno=RET.DATAERR,errmsg = "图片验证码填写错误")

    sms_code = "%06d"%random.randint(0,999999)
    current_app.logger.debug("短信验证码是 = %s" % sms_code)

    try:
        cpp = CCP()
        result = cpp.send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES/60],1)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg = "云通讯异常")

    if result == -1:
        return jsonify(errno=RET.DATAERR,errmsg = "短信发送失败")

    try:
        redis_store.set("sms_code:%s"%mobile,sms_code,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "短信验证码保存失败")
    return jsonify(errno=RET.OK,errmsg = "发送成功")








@passport_blue.route("/image_code")
def image_code():
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")
    if not cur_id:
        return "图片验证码编号不全"
    name,text,image_data = captcha.generate_captcha()
    try:
        redis_store.set("image_code:%s"%cur_id,text,constants.IMAGE_CODE_REDIS_EXPIRES)
        if pre_id:
            redis_store.delete("image_code:%s" % pre_id)

    except Exception as e:
        current_app.logger.error(e)


    response = make_response(image_data)
    response.headers["Content-Type"] = "image/png"
    return response

